package com.nmgolden.lanxin.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nmgolden.lanxin.LanxinAppConfig;
import com.nmgolden.lanxin.LanxinHttpClient;
import com.nmgolden.lanxin.LanxinTokenManager;
import com.nmgolden.lanxin.model.Media;
import org.apache.http.Header;

import java.io.File;
import java.util.List;

/**
 * @author siger
 * @created 2024/5/19
 * @updated 2024/5/19
 */
public class MediaApi extends AbsApi {
    public MediaApi(LanxinAppConfig config, LanxinHttpClient lanxinHttpClient, LanxinTokenManager lanxinTokenManager) {
        super(config, lanxinHttpClient, lanxinTokenManager);
    }

    public JSON uploadMedia(File file, String type) {
        String UPLOAD_MEDIA_TPL = "%s/v1/medias/create?type=%s&app_token=%s";
        String url = String.format(UPLOAD_MEDIA_TPL, mLanxinAppConfig.getApiGateway(), type, mLanxinTokenManager.getAppToken());
        return mLanxinLanxinHttpClient.upload(url, file, "media");
    }

    public void downloadMedia(String mediaId, String location) {
        String DOWNLOAD_TPL = "%s/v1/medias/%s/fetch?app_token=%s";
        String url = String.format(DOWNLOAD_TPL, mLanxinAppConfig.getApiGateway(), mediaId, mLanxinTokenManager.getAppToken());
        mLanxinLanxinHttpClient.download(url, location);
    }

    public Media getMedia(String mediaId) {
        String GET_MEDIA_TMP = "%s/v1/medias/%s/path/fetch?app_token=%s";
        String url = String.format(GET_MEDIA_TMP, mLanxinAppConfig.getApiGateway(), mediaId, mLanxinTokenManager.getAppToken());
        JSONObject jsonObject = mLanxinLanxinHttpClient.get(url);

        Media media = jsonObject.toJavaObject(Media.class);
        media.setId(mediaId);
        return media;
    }

    /**
     * 通过 shareId 获取文件名
     */
    public List<Header> getHeadersByShareId(String shareId)  {
        if (shareId == null || shareId.isEmpty()){
            return null;
        }
        String DOWNLOAD_TPL = "%s/v1/media/share/%s/fetch?app_token=%s";
        String url = String.format(DOWNLOAD_TPL, mLanxinAppConfig.getApiGateway(), shareId, mLanxinTokenManager.getAppToken());
        return mLanxinLanxinHttpClient.getHeaders(url);
    }

    public void downloadByShareId(String shareId, String path){
        String DOWNLOAD_TPL = "%s/v1/media/share/%s/fetch?app_token=%s";
        String url = String.format(DOWNLOAD_TPL, mLanxinAppConfig.getApiGateway(), shareId, mLanxinTokenManager.getAppToken());
        mLanxinLanxinHttpClient.download(url, path);
    }


}
